package cn.glenn.egnotice2.controller;

import cn.glenn.egnotice2.base.response.JsonResult;
import cn.glenn.egnotice2.mapper.NoticeMapper;
import cn.glenn.egnotice2.pojo.dto.NoticeAddParam;
import cn.glenn.egnotice2.pojo.dto.NoticeAddQuery;
import cn.glenn.egnotice2.pojo.dto.NoticeUpdateParam;
import cn.glenn.egnotice2.pojo.enity.Notice;
import cn.glenn.egnotice2.pojo.vo.NoticeDetailInfoVO;
import cn.glenn.egnotice2.pojo.vo.NoticeListVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/v1/notice/")
@Slf4j
public class NoticeController {
    @Autowired
    private NoticeMapper noticeMapper;

    @PostMapping("add")
    public JsonResult addNotice(@RequestBody NoticeAddParam param) {
        log.debug("addNotice param:{}", param);
        Notice notice = new Notice();
        BeanUtils.copyProperties(param, notice);
        notice.setUserId(1L);
        notice.setCreateTime(new Date());
        notice.setUpdateTime(new Date());
        int num = noticeMapper.insertNotice(notice);
        log.debug("addNotice notice:{}", notice);
        if (num > 0) {return JsonResult.success();}
        else return JsonResult.fail();
    }

    @GetMapping("list")
    public JsonResult getNoticeList(NoticeAddQuery query) {
        log.debug("getNoticeList query:{}", query);
        List<NoticeListVO> noticeListVOS = noticeMapper.listNotice(query);
        log.debug("getNoticeList noticeListVOS:{}", noticeListVOS);
        if (!noticeListVOS.isEmpty()) {return JsonResult.success(noticeListVOS);}
        else return JsonResult.fail();
    }

    @GetMapping("detail")
    public JsonResult noticeDetail(Long id) {
        NoticeDetailInfoVO noticeDetailInfoVO = noticeMapper.getNoticeDetailInfo(id);
        log.debug("noticeDetailInfoVO:{}", noticeDetailInfoVO);
        if (noticeDetailInfoVO != null) {return JsonResult.success(noticeDetailInfoVO);}
        else return JsonResult.fail();
    }

    @PostMapping("del")
    public JsonResult deleteNotice(Long id) {
        int num = noticeMapper.deleteNotice(id);
        if (num > 0) {return JsonResult.success();}
        else return JsonResult.fail();
    }

    @PostMapping("update")
    public JsonResult updateNotice(@RequestBody NoticeUpdateParam param) {
        Notice notice = new Notice();
        BeanUtils.copyProperties(param, notice);
        notice.setUpdateTime(new Date());
        int num = noticeMapper.updateNotice(notice);
        if (num > 0) {return JsonResult.success();}
        else return JsonResult.fail();
    }
}
